<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { StoreManagementList,editorialStore,StoreManagementListTable } from '@/api/BussinessMenage/index.js'
import { openService,openPaymentService } from '@/api/OperationManage/index.js' 
import CommonDialog from '@/components/UserDialog/CommonDialog.vue'
import EditDialog from './components/EditDialog.vue'
import { useDistInfoStore } from '@/stores/dict.js'
import { useglobalStore } from '@/stores/global.js'
const globalStore = useglobalStore();
const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();
const distInfoStore = useDistInfoStore();


// 经营品牌数据
const operBrandList = computed(()=>{
    return distInfoStore.getDistInfos("经营品牌").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})

//门店分组列表 
const storeList = computed(()=>{
    return distInfoStore.getDistInfos("门店分组").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})

// 编辑数据回显



// dialog 九养云业务弹框组件

const dialogVisible = ref(false)
// 弹框文字
const dialogTitle = ref('')

const backForm = ref({
  enterpriseId:'',
  storeId:'',
  busiType:1,
  startTime:'',
  endTime:'', 
  remark:'',
  storeName:'',//门店名称
  licenseName:'',//营业执照名称
})

const changeDialog = (val) => {
    dialogVisible.value = val
}
 
const submitDialog = async(val) => {
  console.log(val,'val');
  let data = {
    ...val,
    contract:val.contractObj.fileUrl,
    contractName:val.contractObj.fileName,
    startTime:val.date[0],
    endTime:val.date[1]
  }
  // console.log(data,'data');
  // return
  try {
     const res = await openService(data)
     console.log(res,'res');
     ElMessage.success('开通成功')
     dialogVisible.value = false
     seachTable.value.initSearch();
  } catch (error) {
    
  }finally{

  }
}

// 九养云支付弹框组件
const dialogPayVisible = ref(false)
// 弹框文字
const backPayForm = ref({
  enterpriseId:'',
  storeId:'',
  channel:1,
  remark:'',
  storeName:'',//门店名称
  licenseName:'',//营业执照名称
})

const changePayDialog = (val) => {
  dialogPayVisible.value = val
}

const submitPay = async(val) => {
  console.log(val,'val');
 
  try {
    const res = await openPaymentService(val)
    // console.log(res,'res');
    dialogPayVisible.value = false
    seachTable.value.initSearch();
  } catch (error) {
    
  }finally{

  }
}

// 操作栏目下拉选择
const handleCommand = (val) => {
  if(val == 1){
      dialogTitle.value = '开通九养云业务'
      dialogVisible.value = true
  }else{
      dialogTitle.value = '开通九养云支付业务'
      dialogPayVisible.value = true
  }
}

// 定时请求
let timer = null

// 新增编辑回退时候刷新列表
onActivated(()=>{

    let closeTagName = sessionStorage.getItem('closeTagName');
    if(closeTagName == 'storeManageEdit'){
        seachTable.value.handlerSearch();
        
    }else if(globalStore.business || globalStore.storeId.length > 0 || globalStore.bandId.length > 0){
      // console.log(globalStore.business,'执行了');
      formInline.value[2].model = globalStore.business ? globalStore.business : ""
      filterStore(storeList,5,globalStore.storeId,storeList.value)
      filterStore(operBrandList,4,globalStore.bandId,operBrandList.value)
      timer = setTimeout(() => {
        seachTable.value.initSearch();
      },100)
    }else{
      seachTable.value.initSearch();
    }
    instance.proxy.$forceUpdate();
    sessionStorage.removeItem('closeTagName');
})

const filterStore = (oldDta,index,comparativeData,options) => {

  let result = comparativeData.length === 0 ? [] : oldDta?.value.filter(item => comparativeData.includes(item.value))
  formInline.value[index].data = options
  formInline.value[index].model = result.map(v => {
  return v.value
})

}

onBeforeUnmount(() => {
  console.log(timer,'timer');
  clearTimeout(timer)
  timer = null
  globalStore.setAllClear()
})


// 表格控件
const formInline = ref([
    {
      type: "datePicker",
      prop: ["beginTime", "endTime"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
    {
      type: "input",
      prop: "keywords",
      placeholder: "门店名称/ID",
      label: "",
      model: ""
    },
    {
      type: "input",
      prop: "enterpriseName",
      placeholder: "所属商户",
      label: "",
      handleInput(val) {
        globalStore.business = val;
      },
      model: "",
    },
    {
        type: "select",
        placeholder: "经营方式",
        label: '',
        prop: 'managementWays',
        multiple:true,
        data:[
            {
                label:"直营",
                value:1
            },
            {
                label:"加盟",
                value:2
            }
        ],
        model: [],
        clearable:true 
    },
    {
        type: "select",
        placeholder: "经营品牌",
        label: '',
        prop: 'brandIds',
        multiple:true,
        handleChange:(val) => {
          globalStore.bandId = val
        },
        data:storeList.value,
        model: [],
        data:operBrandList.value,
        model: [],
    },
    {
        type: "select",
        placeholder: "门店分组",
        label: '',
        prop: 'storeGroupIds', 
        multiple:true,
        handleChange:(val) => {
          globalStore.storeId = val
        },
        data:storeList.value,
        model: [],
    },
    {
      type: "input",
      prop: "address",
      placeholder: "所属地区",
      label: "",
      model: "",
    },
])

const btnLefts = ref([
    // {
    //     label:"新增",
    //     plain:false,
    //     type:"primary",
    //     show:true,
    //     img:new URL("@/assets/icon/btn-add.png",import.meta.url),
    //     click:async ()=>{
    //         router.push({name:"merchantChildManageAdd"})
    //     }
    // },

])
const btnRights = ref([
    // {
    //     label:"导出",
    //     plain:false,
    //     plain:true,
    //     show:true,
    //     img:new URL("@/assets/icon/btn-export.png",import.meta.url),
    //     style:"border-color:#0C268C;color:#0C268C",
    //     click:async ()=>{

    //     }
    // }
])

const tableConfig = ref([
    {
      prop: "code",
      label: "门店ID",
      width:200
    },
    {
      prop: "licenseName",
      label: "营业执照名称",
      width:200
    },
    {
      prop: "storeName",
      label: "门店名称",
      width:200
    },
    {
      prop: "enterpriseName",
      label: "所属商户",
      width:200
    },
    {
      prop: "managementWay",
      label: "经营方式",
      format:(val) => {
        return val ? val == 1 ? '直营' : '加盟' : '-'
      },
      width:200
    },
    {
      prop: "brandId",
      label: "经营品牌",
      format: (val) => {
       if(val){
        let newArray = val.split(',')
        let matches = []
        for (const valueToMatch of newArray) {
            const matchingItem = operBrandList.value.find(item => item.value === valueToMatch);
            if (matchingItem) { 
                matches.push(matchingItem.label);
            }
          }
          return matches.join(",");
        }else{
          return '-'
        }
       },
      width:200
    },
    {
      prop: "linkman",
      label: "联系人",
      width:200
    },
    {
      prop: "phone",
      label: "手机号码",
      width:200
    },
    {
      prop: "addr",
      label: "所属地区",
      width:200
    },
    {
      prop: "storeGroupId",
      label: "门店分组",
      format: (val) => {
       if(val){
        let newArray = val.split(',')
        let matches = []
        for (const valueToMatch of newArray) {
            const matchingItem = storeList.value.find(item => item.value === valueToMatch);
            if (matchingItem) { 
                matches.push(matchingItem.label);
            }
          }
          return matches.join(",");
        }else{
          return '-'
        }
       },
      width:200
    },
    {
      prop: "remark",
      label: "备注",
      width:500
    },
    {
      prop: "type",
      label: "开通业务",
      width:200,
      format:(value) => {
        return value ? value == 2 ? '-' : value == 3 ? '九养云' : value == 1 ? '九养云/九养云支付' : '-' : '-'
        // if(value && value == 2){
        //   return '-'
        // }else if(value && value == 3){
        //   return '九养云'
        // }else if(value && value == 1){
        //   return '九养云/九养云支付'
        // }
      }
    },
    {
      prop: "creator",
      label: "创建人",
      width:200
    },
    {
      prop: "createTime",
      label: "创建时间",
      width:200
    },
    {
      type: "action", 
      label: "操作",
      width: 350,
      btns: [
        {
          label: () => "编辑",
          type:"success",
          show:(row)=>{
            return true;
          },
          click: async (row) => {
            // dialogTitle.value = '编辑'
            // dialogVisible.value = true
            router.push({name:"storeManageEdit",query:{id:row.id}})
          },
        },   
        {
          label: () => "开通九养云",
          type:"primary",
          show:(row)=>{
            if(row.type == 2){
              return true;
            }else{
              return false;
            }
            
          },
          click: async (row) => {
            backForm.value.storeName = row.storeName
            backForm.value.licenseName = row.licenseName
            backForm.value.enterpriseId = row.enterpriseId
            backForm.value.storeId = row.id
            dialogTitle.value = '开通九养云业务'
            dialogVisible.value = true
          },
        },   
        {
          label: () => "开通九养云支付",
          type:"primary",
          show:(row)=>{
            if(row.type == 3){
              return true;
            }else{
              return false
            }
           
          },
          click: async (row) => {
            backPayForm.value.storeName = row.storeName
            backPayForm.value.licenseName = row.licenseName
            backPayForm.value.enterpriseId = row.enterpriseId
            backPayForm.value.storeId = row.id
            dialogTitle.value = '开通九养云支付业务'
            dialogPayVisible.value = true
          },
        },   
        // {
        //   type:'slot',
        //   slotName:'openBuss',
        // }, 
      ],  
    },
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);


const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{
        let data = {
          ...formInline
        }
        const res = await StoreManagementListTable(data)
        // console.log(res,'res');
        totalPage.value = res.total;
        tableData.value = res.records;
       
    }catch(e){
  
    }finally{
      tableLoading.value = false;
    }
}



</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :forms="formInline"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :totalPage="totalPage"
          tableHeight="calc(100% - 202px)"
          :noResetTable="true"
          @handlerSearch="handlerSearch"
        >
          <template #openBuss="{row,index}">
            <el-dropdown trigger="click" style="margin-left:8px;" @command="handleCommand">
              <el-button plain type="primary" size="small"  >
                开通业务<el-icon ><CaretBottom /></el-icon>
              </el-button>
              <!-- <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="1">九养云</el-dropdown-item>
                  <el-dropdown-item :command="2">九养云支付</el-dropdown-item>
                </el-dropdown-menu>
              </template> -->
            </el-dropdown>
          </template>
        </SeachTable>
        <common-dialog 
        v-if="dialogVisible"
        :dialogVisible="dialogVisible"
        :dialogTitle="dialogTitle"
        :backForm="backForm"
        @changeDialog="changeDialog"
        @submitDialog="submitDialog"
        ></common-dialog>
        <edit-dialog
        v-if="dialogPayVisible"
        :dialogTitle="dialogTitle"
        :dialogVisible="dialogPayVisible"
        :backForm="backPayForm"
        @changeDialog="changePayDialog"
        @submitPay="submitPay"
        ></edit-dialog>
                </div>
            </template>

<style lang="less" scoped>
    .dialog-main{
        .title-show {
            margin:6px 0 16px 0;
            padding: 12px;
            width: 468px;
            height: 66px; 
            background: rgba(52, 128, 255, 8%);
            // opacity: 8%;
            box-sizing: border-box;
            .buss-pic{
              
            }
            .door-info{
                margin-bottom: 12px;
                color: #3480ff;
                font-family: "PingFang SC";
                font-size: 16px;
                font-style: normal;
                font-weight: 600;
                line-height: 16px;
            }
        }
        .el-form-item{
            margin-bottom: 16px;
            :deep(.el-input) {
                width: 374px;
            }
          
         }
    }
   
</style>